package org.foreningsgatan.modular.terrain.generator;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import org.foreningsgatan.modular.terrain.model.Layer;
import org.foreningsgatan.modular.terrain.model.SimpleMap;

/**
 * 
 * Copyright (c) 2008 Joakim Back
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * @author Joakim Back
 * 
 */
public class LayerGenerator {
	private static Set<Object> idetifyLayers(SimpleMap map) {
		Set<Object> objects = new TreeSet<Object>();

		int size = map.getSize();

		for (int y = 0; y < size; y++) {
			for (int x = 0; x < size; x++) {
				objects.add(map.get(x, y));
			}
		}

		return objects;
	}

	private static Layer buildLayer(SimpleMap map, Object object) {
		int size = map.getSize() + 1;

		Layer layer = new Layer(size, object);

		for (int y = 0; y < size; y++) {
			for (int x = 0; x < size; x++) {
				Object o = map.get(x, y);

				if (o != null && o.equals(object)) {
					layer.set(x, y);
				}
			}
		}

		return layer;
	}

	public static Set<Layer> generateLayers(SimpleMap map) {
		Set<Layer> layers = new HashSet<Layer>();

		for (Object o : idetifyLayers(map)) {
			layers.add(buildLayer(map, o));
		}

		return layers;
	}
}
